import React, { PureComponent, Fragment } from 'react';
import { Card, Checkbox, message, Radio } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import _ from 'lodash';
import router from 'umi/router';
import ProjectsPath from '@/components/ProjectsPath';
import CurrentStage from '../components/CurrentStage';
import PageEmpty from '@/components/PageEmpty';
import PageTop from './components/PageTop';
import styles from '../../index.less';
import * as apis from '@/services/ContractPlanMgr';
import { showConfirm } from '@/utils/utils';
import { getTitleTree, getFixedColumns } from './utils/tableUtils';
import Btns from '@/components/Btns';
import { handlerMatomoEvent } from '@/utils/matomo';
import { BaseTable, utils } from '@/components/BaseTable';
import moment from 'moment';

const VERSION_STATE_NAME = {
  dynamic: '月度动态版',
  budget: '预算版',
  strategy: '战规版',
  investment: '投资版',
};

@connect(state => ({
  items: state.ContractPlanItems,
  versions: state.ContractPlanVersions,
  Permissions: state.Permissions,
  orgStructure: state.orgStructure,
  overAllYears: state.ContractPlanItems.overAllYears,
  currentYear: state.ContractPlanItems.currentYear,
  currentMonths: state.ContractPlanItems.currentMonths,
  // loading: state.loading.models.items,
}))
export default class ContractPlan extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      emptyMsg: '',
      loading: false,
      setBudgetVersionLoading: false,
    };
  }

  async componentDidMount() {
    const { match } = this.props;
    this.clearItems();
    this.clearVersions();
    this.getVersions(this.props);

    if (match.params.version) {
      this.clearItems();
      this.getItems(this.props);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (
      this.props.match.params.project !== nextProps.match.params.project ||
      this.props.match.params.stage !== nextProps.match.params.stage ||
      this.props.match.params.category !== nextProps.match.params.category
    ) {
      this.clearItems();
      this.getVersions(nextProps);
    }

    if (
      nextProps.match.params.version &&
      this.props.match.params.version !== nextProps.match.params.version
    ) {
      this.clearItems();
      this.getVersions(nextProps, this.getItems(nextProps));
    }
  }

  getVersions = (props, cb) => {
    const { dispatch, match } = props;
    const params = {
      projectFid: match.params.stage,
      versionType: props.match.params.category,
    };
    const self = this;
    let callback = cb;
    if (!cb) {
      callback = versions => {
        // 如果:version==null 跳转第一个version
        if (versions && !match.params.version) {
          router.replace(
            `/OperatingPlan/ContractPlan/${match.params.level1}/${match.params.level2}/${match.params.project}/${match.params.stage}/${match.params.category}/${versions[0].versionId}`,
          );
        } else if (versions && match.params.version) {
          router.replace(`${this.props.location.pathname}`);
        } else {
          self.setState({ emptyMsg: '版本不存在，请先创建新版本' });
        }
      };
    }
    // 获取versions
    dispatch({
      type: 'ContractPlanVersions/fetch',
      payload: { params },
      callback,
    });
  };

  clearItems = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ContractPlanItems/clear',
    });
  };

  clearVersions = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ContractPlanVersions/clear',
    });
  };

  getItems = props => {
    const self = this;
    const { dispatch, match } = props;
    if (match.params.version) {
      const params = {
        versionId: match.params.version,
        // stage: match.params.stage,
      };
      this.setState({ emptyMsg: '版本数据加载中...' });
      dispatch({
        type: 'ContractPlanItems/init',
        payload: {
          params,
          category: props.match.params.category,
        },
        callback: data => {
          if (_.isEmpty(data)) {
            self.setState({ emptyMsg: '版本不存在，请先创建新版本' });
          }
        },
      });
    }
  };

  // 审批校验-预览
  approval = () => {
    const { dispatch, match } = this.props;
    const { project, version } = match.params;
    const params = {
      projectId: project,
      versionId: version || '',
    };
    dispatch({
      type: 'ContractPlanItems/approval',
      payload: {
        params,
      },
      callback: () => {
        // 签约审批 - 埋点
        handlerMatomoEvent({
          category: 'Page',
          action: '签约计划-签约审批',
          name: '签约计划-签约审批',
        });
        window.open(
          `${window.location.origin}/#/common/SigningApprove?action=modify&projectId=${project}`,
        );
      },
    });
  };

  // 签约计划重新打考核标签
  setVersionAssessment = params => {
    showConfirm(
      () => {
        apis
          .settingsAssessmentVersionUsingGET({ params: { versionId: params.version } })
          .then(result => {
            if (result && result.code === 1) {
              message.success(result.message, () => {
                window.location.reload();
              });
            }
          });
      },
      '设置考核版',
      '确定将此版本设为考核版吗？',
    );
  };

  /**
   * @Descripttion: 设置预算版
   * @param {*}
   * @return {*}
   */
  setBudgetVersion = () => {
    // 获取预算版本标签
    apis.commonBudgetVersion({}).then(response => {
      let content = `非预算季时，复制为${moment().year()}年定稿版预算版`;
      if (response?.code === 1) {
        if (!_.isEmpty(response.data)) {
          content = `确认后将基于（${response.data}）手动设置预算版本。`;
        }
        showConfirm(
          () => {
            this.setState({
              setBudgetVersionLoading: true,
            });
            // 请求手动设置预算版本
            apis
              .signPlanVersionCopyBudgetVersion({
                params: {
                  versionId: this.props.match.params.version,
                },
              })
              .then(res => {
                if (res.code === 1 && res.data === 'ok') message.success('设置成功', 1);
              })
              .then(() => {
                this.setState({
                  setBudgetVersionLoading: false,
                });
              });
          },
          '手动设置预算版本',
          content,
        );
      }
    });
  };

  /**
   * @Descripttion: 复制预算版
   * @param {*}
   * @return {*}
   */
  copyBudgetVersion = () => {
    const self = this;
    const { match } = this.props;
    const callback = versions => {
      if (!_.isEmpty(versions)) {
        router.replace(
          `/OperatingPlan/ContractPlan/${match.params.level1}/${match.params.level2}/${
            match.params.project
          }/${match.params.stage}/${match.params.category}/${_.head(versions).versionId}`,
        );
      } else {
        self.setState({ emptyMsg: '版本不存在，请先创建新版本' });
        router.replace(
          `/OperatingPlan/ContractPlan/${match.params.level1}/${match.params.level2}/${match.params.project}/${match.params.stage}/${match.params.category}`,
        );
      }
    };
    apis.commonBudgetVersion({}).then(response => {
      let content = `非预算季时，复制为${moment().year()}年定稿版预算版`;
      if (response?.code === 1) {
        if (!_.isEmpty(response.data)) {
          content = `确认后将基于（${response.data}）手动复制预算版本。`;
        }
        showConfirm(
          () => {
            this.setState(
              {
                setBudgetVersionLoading: true,
              },
              () => {
                // 请求手动设置预算版本
                apis
                  .signPlanVersionCopySignPlanVersion({
                    params: {
                      versionId: this.props.match.params.version,
                    },
                  })
                  .then(res => {
                    if (res.code === 1 && res.data === 'ok') {
                      message.success('设置成功', 1, self.getVersions(self.props, callback));
                    }
                  })
                  .then(() => {
                    this.setState({
                      setBudgetVersionLoading: false,
                    });
                  });
              },
            );
          },
          '手动复制预算版本',
          content,
        );
      }
    });
  };

  changeCurrentMonths = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ContractPlanItems/changeCurrentMonths',
      payload: {
        currentMonths: value,
      },
    });
  };

  // 删除版本
  async deletePriceVersion() {
    const self = this;
    const { version } = this.props.match.params;
    const { match } = this.props;
    const params = {
      versionId: version,
    };

    const callback = v => {
      // 如果:version==null 跳转第一个version
      if (v && v.length > 0) {
        router.replace(
          `/OperatingPlan/ContractPlan/${match.params.level1}/${match.params.level2}/${match.params.project}/${match.params.stage}/${match.params.category}/${v[0].versionId}`,
        );
      } else {
        self.setState({ emptyMsg: '版本不存在，请先创建新版本' });
        router.replace(
          `/OperatingPlan/ContractPlan/${match.params.level1}/${match.params.level2}/${match.params.project}/${match.params.stage}/${match.params.category}`,
        );
      }
    };
    const data = await apis.deleteSignPlanVersionUsingDELETE({ params });
    if (data.code === 1) {
      message.success(data.message);
      self.getVersions(self.props, callback);
    }
  }

  // 创建版本
  confirmCreateVersion() {
    const self = this;
    let budgetLabelOptions = []; // 预算版标签容器
    let budgetLabelValue = []; // 预算版标签默认选中的值
    const { stage, category, level1, level2, project } = this.props.match.params;
    // 请求创建版本
    const requestCreateVersion = versionIdentify => {
      const params = {
        projectFid: stage,
        versionType: category,
        versionIdentify,
      };
      apis
        .createSignPlanVersionUsingPOST({ params })
        .then(data => {
          if (data && data.code === 1) {
            router.push(
              `/OperatingPlan/ContractPlan/${level1}/${level2}/${project}/${stage}/${category}/${data.data}`,
            );
          }
        })
        .then(() => {
          self.setState({
            loading: false,
          });
        });
    };
    // 获取预算版本标签
    apis
      .commonBudgetVersion({})
      .then(res => {
        if (res?.code === 1 && !_.isEmpty(res.data)) {
          budgetLabelOptions = [{ label: res.data, value: res.data }];
          budgetLabelValue = [_.head(budgetLabelOptions).value];
        }
      })
      .then(() => {
        // 弹出确认框
        showConfirm(
          () => {
            this.setState({
              loading: true,
            });
            // 如果有选中的预算版标签-校验是否可以创建
            if (!_.isEmpty(budgetLabelValue)) {
              apis
                .commonCreateBudgetVerify({
                  params: {
                    projectId: project,
                    stageId: stage,
                    type: 'sign',
                  },
                })
                .then(res => {
                  if (res.code === 1 && res.data === 'ok') {
                    requestCreateVersion(_.head(budgetLabelValue));
                  } else {
                    this.setState({
                      loading: false,
                    });
                  }
                });
            } else {
              requestCreateVersion('');
            }
          },
          `确认创建新版${VERSION_STATE_NAME[category]}签约计划吗？`,
          <Checkbox.Group
            options={budgetLabelOptions}
            defaultValue={budgetLabelValue}
            onChange={checkedValue => {
              budgetLabelValue = checkedValue;
            }}
          />,
        );
      });
  }

  // 创建异常版本
  createPriceAbnormalVersion() {
    const self = this;
    let budgetLabelOptions = []; // 预算版标签容器
    let budgetLabelValue = []; // 预算版标签默认选中的值
    const { stage, category, level1, level2, project } = this.props.match.params;
    // 请求创建版本
    const requestExceptionCreateVersion = versionIdentify => {
      const params = {
        projectFid: stage,
        versionType: category,
        versionIdentify,
      };
      apis
        .exceptionCreateSignPlanVersionUsingPOST({ params })
        .then(data => {
          if (data && data.code === 1) {
            router.push(
              `/OperatingPlan/ContractPlan/${level1}/${level2}/${project}/${stage}/${category}/${data.data}`,
            );
          }
        })
        .then(() => {
          self.setState({
            loading: false,
          });
        });
    };
    // 获取预算版本标签
    apis
      .commonBudgetVersion({})
      .then(res => {
        if (res?.code === 1 && !_.isEmpty(res.data)) {
          budgetLabelOptions = [{ label: res.data, value: res.data }];
          budgetLabelValue = [_.head(budgetLabelOptions).value];
        }
      })
      .then(() => {
        // 弹出确认框
        showConfirm(
          () => {
            this.setState({
              loading: true,
            });
            // 如果有选中的预算版标签-校验是否可以创建
            if (!_.isEmpty(budgetLabelValue)) {
              apis
                .commonCreateBudgetVerify({
                  params: {
                    projectId: project,
                    stageId: stage,
                    type: 'sign',
                  },
                })
                .then(res => {
                  if (res.code === 1 && res.data === 'ok') {
                    requestExceptionCreateVersion(_.head(budgetLabelValue));
                  } else {
                    this.setState({
                      loading: false,
                    });
                  }
                });
            } else {
              requestExceptionCreateVersion('');
            }
          },
          `点击确认后创建(签约计划)${VERSION_STATE_NAME[category]}-异常版本。`,
          <Checkbox.Group
            options={budgetLabelOptions}
            defaultValue={budgetLabelValue}
            onChange={checkedValue => {
              budgetLabelValue = checkedValue;
            }}
          />,
        );
      });
  }

  /* 点击年份表格头年份请求数据 */
  changeCurrentYear(value) {
    const { dispatch } = this.props;
    const self = this;
    dispatch({
      type: 'ContractPlanItems/changeCurrentYear',
      payload: {
        currentYear: value,
      },
      callback: () => {
        self.getItems(self.props);
      },
    });
  }

  yearsRender() {
    let node;
    const { overAllYears, currentYear } = this.props.items;
    const { scrollRight } = this.state;
    if (overAllYears.length) {
      node = (
        <div style={!scrollRight ? { position: 'fixed', right: '40px' } : null}>
          <Radio.Group
            onChange={ev => this.changeCurrentYear(ev.target.value)}
            defaultValue={currentYear}
            buttonStyle="solid"
            size="small"
          >
            {overAllYears.map((element, index) => {
              if (index <= 15) {
                return (
                  <Radio.Button key={element} value={element}>
                    {element}
                  </Radio.Button>
                );
              }
            })}
            {overAllYears.length > 15 && <Radio.Button disabled>...</Radio.Button>}
          </Radio.Group>
        </div>
      );
    }
    return node;
  }

  render() {
    const { loading } = this.state;
    const { versions, items, match, currentYear, currentMonths } = this.props;
    const { expandedRowKeys, searched } = items;
    const { params } = this.props.match;
    const treeData = searched;
    let edit = false;
    let versionState = '';
    let currentState = [];
    if (versions && versions.data.length > 0 && params.version) {
      currentState = _.filter(versions.data, { versionId: params.version });
      if (currentState.length) {
        versionState = currentState[0].versionStateCode;
      }
      if (
        _.includes(this.props.Permissions.buttons, 'button_1040204') &&
        (versionState === 'not_prepared' ||
          versionState === 'organization' ||
          versionState === 'examined_approved' ||
          versionState === 'failure_approved')
      ) {
        edit = true;
      }
    }

    let fixedColumns = [];
    let titleTree = [];
    if (currentYear) {
      titleTree = getTitleTree(currentYear, currentMonths);
      fixedColumns = getFixedColumns(currentYear, edit, this.props, currentMonths);
    }
    const headerRenderer = utils.getHeaderRenderer(titleTree, 4, e => this.yearsRender(e));
    return (
      <PageHeaderWrapper
        className="page-header"
        breadcrumb={null}
        title={<ProjectsPath {...this.props} />}
        tags={<CurrentStage {...this.props} />}
        extra={
          <Btns
            rowAttribute={{
              gutter: [5, 0],
              type: 'flex',
              justify: 'space-between',
              align: 'middle',
            }}
            BtnsList={[
              {
                authority: 'business_signing_submitApproval',
                value: '发起审批',
                btnAttribute: {
                  onClick: () => this.approval(),
                  type: 'primary',
                },
              },
              {
                authority: 'business_signing_approvalRecord',
                value: '审批记录',
                btnAttribute: {
                  onClick: () =>
                    router.push(`/OperatingPlan/ContractPlan/ProjectValue/${match.params.project}`),
                },
              },
            ]}
          />
        }
      >
        <Card className="page-header-card">
          <div className={styles.container}>
            <PageTop
              createPriceVersion={() => this.confirmCreateVersion()}
              deletePriceVersion={() => this.deletePriceVersion()}
              createPriceAbnormalVersion={() => this.createPriceAbnormalVersion()}
              setVersionAssessment={this.setVersionAssessment}
              handleExportReportForm={() => this.handleExportReportForm()}
              setBudgetVersion={this.setBudgetVersion}
              copyBudgetVersion={this.copyBudgetVersion}
              loading={loading}
              setBudgetVersionLoading={this.state.setBudgetVersionLoading}
              getItems={this.getItems}
              {...this.props}
            />
            {this.props.match.params.version && fixedColumns.length > 0 && treeData.length > 0 ? (
              <Fragment>
                <BaseTable
                  subtractHeight="210px"
                  defaultExpandedRowKeys={expandedRowKeys}
                  expandColumnKey="name"
                  rowKey="signDetailId"
                  fixedColumns={fixedColumns}
                  headerHeight={[30, 30, 30, 30, 30]}
                  headerRenderer={headerRenderer}
                  treeData={treeData}
                />
              </Fragment>
            ) : (
              <PageEmpty emptyTitle={this.state.emptyMsg} />
            )}
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
